﻿namespace XGameLibrary.ScreenManager
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Xna.Framework;

    public class GameState : DrawableGameComponent
    {
        public GameState(Game game, GameStateManager manager) :
            base(game)
        {
            this.Components = new List<GameComponent>();
            this.Tag = this;
            this.StateManager = manager;
        }

        public List<GameComponent> Components { get; private set; }

        public GameState Tag { get; private set; }

        protected GameStateManager StateManager { get; set; }

        public override void Update(GameTime gameTime)
        {
            foreach (var component in this.Components)
            {
                if (component.Enabled)
                {
                    component.Update(gameTime);
                }
            }

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            DrawableGameComponent drawableComponent;

            foreach (var component in this.Components)
            {
                if (component is DrawableGameComponent)
                {
                    drawableComponent = component as DrawableGameComponent;

                    if (drawableComponent.Visible)
                    {
                        drawableComponent.Draw(gameTime);
                    }
                }
            }

            base.Draw(gameTime);
        }

        protected internal virtual void StateChange(object sender, EventArgs e)
        {
            if (this.StateManager.CurrentState == this.Tag)
            {
                this.Show();
            }
            else
            {
                this.Hide();
            }
        }

        protected virtual void Show()
        {
            this.Visible = true;
            this.Enabled = true;

            foreach (var component in this.Components)
            {
                component.Enabled = true;
                if (component is DrawableGameComponent)
                {
                    (component as DrawableGameComponent).Visible = true;
                }
            }
        }

        protected virtual void Hide()
        {
            this.Visible = false;
            this.Enabled = false;

            foreach (var component in this.Components)
            {
                component.Enabled = false;
                if (component is DrawableGameComponent)
                {
                    (component as DrawableGameComponent).Visible = false;
                }
            }
        }
    }
}
